const Koa = require("koa");
const Router = require("@koa/router");
const OSS = require('ali-oss');
const { STS } = require('ali-oss')
// 禁用 AWS SDK v2 的弃用警告
process.env.AWS_SDK_JS_SUPPRESS_MAINTENANCE_MODE_MESSAGE = '1';
const AWS = require('aws-sdk');
const cors = require("koa2-cors");
const { koaBody } = require("koa-body"); // 引入 koa-body
require("dotenv").config();
const habitRouter = require("./habit");
const hautyRouter = require("./hauty");
const lampRouter = require("./lamp");
const { router: userRouter } = require("./user");
const noteRouter = require("./note");
const { router: googleOAuthRouter } = require("./googleOAuth");
const productsRouter = require("./products");
const skiLogRouter = require("./ski_log");
const docRouter = require("./doc");
const contactMsgRouter = require("./contact_msg");
const momentRouter = require("./moment");
const app = new Koa();
const router = new Router();
const { exec } = require("child_process");

// IP限流存储
const ipRateLimit = new Map();

// IP限流中间件
const ipRateLimitMiddleware = async (ctx, next) => {
  const ip = ctx.ip || ctx.request.ip;
  const now = Date.now();
  const oneMinute = 60 * 1000;
  
  // 清理过期记录
  for (const [key, value] of ipRateLimit.entries()) {
    if (now - value.timestamp > oneMinute) {
      ipRateLimit.delete(key);
    }
  }
  
  const ipData = ipRateLimit.get(ip);
  
  if (!ipData) {
    ipRateLimit.set(ip, { count: 1, timestamp: now });
    return next();
  }
  
  if (now - ipData.timestamp > oneMinute) {
    ipRateLimit.set(ip, { count: 1, timestamp: now });
    return next();
  }
  
  if (ipData.count >= 5) {
    ctx.status = 429;
    ctx.body = {
      success: false,
      message: '请求过于频繁，请稍后再试'
    };
    return;
  }
  
  ipRateLimit.set(ip, { count: ipData.count + 1, timestamp: ipData.timestamp });
  return next();
};

// 配置AWS SDK for Cloudflare R2
const s3 = new AWS.S3({
  endpoint: `https://${process.env.CLOUDFLARE_ACCOUNT_ID}.r2.cloudflarestorage.com`,
  accessKeyId: process.env.CLOUDFLARE_ACCESS_KEY_ID,
  secretAccessKey: process.env.CLOUDFLARE_SECRET_ACCESS_KEY,
  region: 'auto',
  signatureVersion: 'v4'
});

// 配置阿里云OSS客户端
const ossClient = new OSS({
  region: process.env.OSS_REGION || 'oss-cn-guangzhou',
  accessKeyId: process.env.ACCESSKEY_ID,
  accessKeySecret: process.env.ACCESSKEY_SECRET,
  bucket: process.env.OSS_BUCKET || 'hauty'
});

const path = require('path');
const fs = require('fs');

// 确保uploads目录存在
const uploadsDir = path.join(__dirname, '../uploads');
if (!fs.existsSync(uploadsDir)) {
  fs.mkdirSync(uploadsDir, { recursive: true });
}

app.use(koaBody({
  multipart: true,
  formidable: {
    uploadDir: uploadsDir, // 使用绝对路径
    keepExtensions: true,   // 保持文件扩展名
    maxFileSize: 10 * 1024 * 1024, // 最大文件大小 10MB
  }
}));

// 服务端支持跨域
app.use(
  cors({
    origin: "*", // 允许所有域名跨域
    credentials: true, // 允许跨域的时候带着 cookie
  })
);

// 自动部署
router.post("/webhook", async (ctx) => {
  ctx.body = { success: true, message: "部署已开始!" };
  setTimeout(() => {
    exec("/www/wwwroot/pure-koa/deploy.sh", (error, stdout, stderr) => {
      if (error) {
        console.error(`${new Date().toLocaleString()} ❌ 部署失败:`, error.message);
        console.error(stderr);
      } else {
        console.log(`${new Date().toLocaleString()} ✅ 部署成功:\n`, stdout);
      }
    });
  }, 1000);
});

router.get('/sts', async (ctx) => {
  try {
    const sts = new STS({
      accessKeyId: process.env.ACCESSKEY_ID,
      accessKeySecret: process.env.ACCESSKEY_SECRET
    });
    const result = await sts.assumeRole('acs:ram::1067378610196421:role/jue-se-1', `{
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
              "oss:PutObject",
              "oss:GetObject",
              "oss:DeleteObject"
          ],
          "Resource": [
            "acs:oss:*:*:web-note",
            "acs:oss:*:*:web-note/*"
          ]
        }
      ]
    }`, '43200', 'SessionTest');
    ctx.body = {
      AccessKeyId: result.credentials.AccessKeyId,
      AccessKeySecret: result.credentials.AccessKeySecret,
      SecurityToken: result.credentials.SecurityToken,
      Expiration: result.credentials.Expiration
    };
  } catch (err) {
    ctx.status = 400;
    ctx.body = err.message;
  }
});

// 上传文件到阿里云OSS
router.post('/upload-to-oss', ipRateLimitMiddleware, async (ctx) => {
  try {
    const { files } = ctx.request;
    
    if (!files || !files.file) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '没有找到上传的文件'
      };
      return;
    }
    
    const file = files.file;
    
    // 检查文件大小（限制5MB）
    const maxSize = 5 * 1024 * 1024; // 5MB
    const fileSize = file.size || (file.buffer ? file.buffer.length : 0);
    
    if (fileSize > maxSize) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '文件大小不能超过5MB'
      };
      return;
    }
    
    // 生成唯一文件名
    const timestamp = Date.now();
    const randomStr = Math.random().toString(36).substring(2, 8);
    const fileExtension = path.extname(file.originalFilename || file.name);
    const fileName = `moment/${timestamp}_${randomStr}${fileExtension}`;
    
    // 读取文件内容
    const fileContent = file.buffer || fs.readFileSync(file.filepath);
    
    // 上传到OSS
    const result = await ossClient.put(fileName, fileContent, {
      headers: {
        'Content-Type': file.mimetype || file.type
      }
    });
    
    // 返回访问URL
    const fileUrl = result.url;
    
    ctx.body = {
      success: true,
      url: fileUrl,
      key: fileName,
      message: '文件上传成功'
    };
    
    // 清理临时文件
    if (file.filepath && fs.existsSync(file.filepath)) {
      fs.unlinkSync(file.filepath);
    }
    
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: error.message
    };
  }
});

// 上传文件到Cloudflare R2
router.post('/upload-to-r2', async (ctx) => {
  try {
    const { files } = ctx.request;
    
    if (!files || !files.file) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '没有找到上传的文件'
      };
      return;
    }
    
    const file = files.file;
    const bucketName = ctx.request.body.bucket || 'hauty';
    
    const uploadParams = {
      Bucket: bucketName,
      Key: file.originalFilename || file.name,
      Body: file.buffer || require('fs').readFileSync(file.filepath),
      ContentType: file.mimetype || file.type,
    };
    
    const result = await s3.upload(uploadParams).promise();
    
    ctx.body = {
      success: true,
      url: result.Location,
      key: result.Key
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: error.message
    };
  }
});

app.use(router.routes()).use(router.allowedMethods());
app.use(habitRouter.routes()).use(habitRouter.allowedMethods());
app.use(hautyRouter.routes()).use(hautyRouter.allowedMethods());
app.use(lampRouter.routes()).use(lampRouter.allowedMethods());
app.use(userRouter.routes()).use(userRouter.allowedMethods());
app.use(noteRouter.routes()).use(noteRouter.allowedMethods());
app.use(googleOAuthRouter.routes()).use(googleOAuthRouter.allowedMethods());
app.use(productsRouter.routes()).use(productsRouter.allowedMethods());
app.use(skiLogRouter.routes()).use(skiLogRouter.allowedMethods());
app.use(docRouter.routes()).use(docRouter.allowedMethods());
app.use(contactMsgRouter.routes()).use(contactMsgRouter.allowedMethods());
app.use(momentRouter.routes()).use(momentRouter.allowedMethods());
const bannersRouter = require("./banners");
app.use(bannersRouter.routes()).use(bannersRouter.allowedMethods());
app.listen(9000, () => console.log(`${new Date().toLocaleString()} 🚀 http://localhost:9000`));
